// components/mine/info.ts
import { ajax } from "../../utils/request";
import { handleLogin, handleLogout } from "../../utils/login";
import { upload } from '../../utils/qiniuUploader';

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    userInfo: {
      type: Object,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 退出登录
    handleDoLogout() {
      handleLogout(() => {
        this.triggerEvent("loginComplete", false);
        this.setData({ userInfo: null });
      })
    },
    // 登录
    handleDoLogin() {
      handleLogin(loginResult => {
        this.setData({ userInfo: loginResult })
        this.triggerEvent("loginComplete", true);
      })
    },
    // 更改头像
    async handleAvatar() {
      let that = this;

      let res = await ajax("/resource/getToken");
      console.log("Res = ",res);

      let uptoken = res.data.result_data.token;
      let domain = res.data.result_data.remoteAddr;
      
      if (!uptoken) {
        console.log("无法获取token");
        return;
      }

      wx.chooseMedia({
        count: 1,
        mediaType: ["image"],
        success(res: WechatMiniprogram.ChooseMediaSuccessCallbackResult) {
          let tempFiles = res.tempFiles;
          // console.log("file = ", tempFiles[0]);
          console.log("tempFiles.length = ",tempFiles.length);
          if (tempFiles.length < 1) {
            return;
          }
          var filePath = tempFiles[0].tempFilePath;
          let splits = filePath.split(".");
          let suffix = splits.length >= 2 ? "." + splits[splits.length - 1] : "";

          let key = "tcapp-" + new Date().getTime() + suffix;
          console.log("七牛云上传key = ",key);


          upload({
            filePath: filePath,
            options: {
              key,          // 可选
              region: 'SCN',       // 可选(默认为'ECN')
              domain,
              uptoken,      // 以下三选一
              // uptokenURL: '',
              // async uptokenFunc() {
              //   return '[yourTokenString]';
              // },
              shouldUseQiniuFileName: false // 默认true
            },
            before: () => {
              // 上传前
              console.log('before upload');
            },
            success: (res) => {
              // that.setData({
              //   'imageObject': res
              // });
              console.log('file url is: ' , res);
            },
            fail: (err) => {
              console.log('error:' + err);
            },
            // progress: (res) => {
            //   console.log('上传进度', res.progress)
            //   console.log('已经上传的数据长度', res.totalBytesSent)
            //   console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
            // },
            complete: (err) => {
              // 上传结束
              console.log('upload complete');
            }
          });
        }
      })
    }
  }
})
